import { PAGE_SIZES } from '@/constant/modules/paging'
import { randTime, uuid } from '@/utils/modules/random'
import { h } from 'vue'
import { ElLink } from 'element-plus'
import { getTableList2 as getTableList } from '@/api/modules/template'
import omitNotColumnable from '@/utils/modules/omitNotColumnable'

// eslint-disable-next-line
async function getData (params: any) {
  return new Promise<any>((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        data: {
          total: 100,
          thead: [
            { label: '时间', prop: 'time' },
            ...(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']).map(item => ({
              label: `指标名称${item}`,
              prop: item,
            })),
          ],
          tbody: [
            ...Array.from({ length: 100 }).map(() => ({
              time: randTime(),
              ...(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'])
                .reduce((acc, v) => {
                  acc[`${v}_indicatorNumber`] = uuid()
                  acc[v] = (Math.random() * 100).toFixed(2)
                  return acc
                }, {} as any),
            })),
          ],
        },
      })
    }, 400)
  })
}

let cacheModelId: any = null

export function setCacheModelId(id: any) {
  cacheModelId = id
}

export default function useTemplateData(
  clickValue?: (indicatorNumber: string) => void,
  needCacheColumns: boolean = true,
) {
  const [loading, setLoading] = useState(false)
  const [columns, setColumns] = useShallowState<any[]>([])
  const pagination = reactive({
    pageNumber: 1,
    pageSize: PAGE_SIZES[0],
    total: 0,
  })
  const [lists, setLists] = useShallowState<any[]>([])

  async function getLists(params: any) {
    setLoading(true)
    try {
      const { data } = await getTableList(params)
      if (!needCacheColumns || cacheModelId !== params.modelId) {
        setCacheModelId(params.modelId)
        setColumns(
          omitNotColumnable((data.thead ?? []).map((v: any) => ({
            ...v,
            children: v.children ?? [],
            key: uuid(),
            minWidth: v.prop === 'time' ? 140 : 180,
            fixed: v.prop === 'time' ? 'left' : undefined,
            render: v.prop === 'time'
              ? null
              : ({ row, column }: any) => (row[v.prop] != null && row[v.prop] != '-')
                  ? h(
                    ElLink,
                    {
                      type: 'primary',
                      onClick: () => {
                        clickValue?.(column.property)
                      },
                    },
                    () => h('code', row[v.prop]),
                  )
                  : h('span', '-'),
          }))),
        )
      }
      setLists(data.tbody ?? [])
      pagination.total = data.total ?? 0
    }
    finally {
      setLoading(false)
    }
  }

  return {
    loading,
    columns,
    pagination,
    lists,
    getLists,
  }
}
